﻿using StudentMocking.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using StudentMocking.Repositories;
using System.Linq;

namespace StudentMocking.Services
{
    public class StudentsService : IStudentsService
    {
        private ObservableCollection<Student> _students = new ObservableCollection<Student>();

        private IStudentsRepository _studnetsRepository;

        public StudentsService(IStudentsRepository studentsRepository)
        {
            _studnetsRepository = studentsRepository;
        }

        public IEnumerable<Student> students
        {
            get { return _students; }
        }

        public async Task<Student> AddOrUpdateSutdentAnsyc(Student student)
        {
            //如果book为null,抛空异常
            if (student is null) throw new ArgumentNullException(nameof(student));

            //设置一个Book变量updated，用以返回在添加或删除操作后从存储库中传回的书
            Student updated = null;

            //根据bookid判断用户操作是添加还是更新，从而采取不同的仓储策略
            if (student.Id == 0)
            {
                //添加操作，调用存储库添加方法，将书添加到存储库
                updated = await _studnetsRepository.AddStudent(student);
                //同步添加到私有数据集中
                _students.Add(updated);
            }
            else
            {
                //更新操作调用存储库添加方法，将书更新到存储库
                updated = await _studnetsRepository.UpdateStudent(student);
                //如果更新存储库返回null，抛出无效操作异常
                if (updated == null) throw new InvalidOperationException();

                //同步处理私有数据集
                //检索私有数据集中对应的原数据
                Student old = _students.Where(b => b.Id == updated.Id).Single();
                //找出其索引
                int ix = _students.IndexOf(old);
                //将其从数据集中移除
                _students.RemoveAt(ix);
                //将新数据插入到指定索引位置
                _students.Insert(ix, updated);
            }
            return updated;
        }

        public async Task LoadStudentAnsyc()
        {
            if (_students.Count > 0) return;

            IEnumerable<Student> students = await _studnetsRepository.GetStudentsAnsyc();

            _students.Clear();
            foreach (var item in students)
            {
                _students.Add(item);
            }
        }

        public Student Student(int studentid)
        {
            return _students.Where(s => s.Id == studentid).SingleOrDefault();
        }
    }
}
